package org.jeecg.modules.scm.service.impl;


import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.modules.scm.dto.EditInvItemRsDto;
import org.jeecg.modules.scm.entity.ScmInvItemRs;
import org.jeecg.modules.scm.mapper.ScmInvItemRsMapper;
import org.jeecg.modules.scm.service.IScmInvItemRsService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Description: 资金方关联关系信息表服务实现类
 * @Author: zzq
 * @Date: 2021-10-21
 * @Version: V1.0
 */
@Service
public class ScmInvItemRsServiceImpl extends ServiceImpl<ScmInvItemRsMapper, ScmInvItemRs> implements IScmInvItemRsService {

    @Override
    public int save(EditInvItemRsDto dto) {
        dto.setId(0);
        ScmInvItemRs invItemRs = new ScmInvItemRs();
        // 复制属性,忽略id
        BeanUtils.copyProperties(dto, invItemRs, "id");
//        BigDecimal availableCredit = dto.getMonthScaleLimit().subtract();
//        invItemRs.setAvailableCredit(availableCredit);
        // TODO 计算可用额度
        baseMapper.insert(invItemRs);

        return invItemRs.getId();
    }

    @Override
    public boolean update(EditInvItemRsDto dto) {
        ScmInvItemRs invItemRs = new ScmInvItemRs();
        // 复制属性
        BeanUtils.copyProperties(dto, invItemRs);
        // TODO 计算可用额度
        return this.updateById(invItemRs);
    }

    @Override
    public String uploadAccessory(MultipartFile file, Integer id) {
        ScmInvItemRs invItemRs = lambdaQuery().select(ScmInvItemRs::getId, ScmInvItemRs::getAccessory)
                .eq(ScmInvItemRs::getId, id).one();

        if (invItemRs == null) {
            throw new JeecgBootException("项目关联关系不存在");
        }
        String urls = invItemRs.getAccessory();
        String url = CommonUtils.upload(file, "/invItemRs", CommonConstant.UPLOAD_TYPE_MINIO);
        String path = URLUtil.getPath(url);
        if (StringUtils.isEmpty(urls)) {
            urls = path;
        } else {
            urls = urls + "," + path;
        }
        lambdaUpdate().eq(ScmInvItemRs::getId, id)
                .set(StringUtils.isNotBlank(path), ScmInvItemRs::getAccessory, urls)
                .update();

        return urls;
    }
}
